package com.jspgou.cms.action.admin.main;

import static com.jspgou.common.page.SimplePage.cpn;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jspgou.cms.entity.Category;
import com.jspgou.cms.entity.Noctice;
import com.jspgou.cms.entity.Store;
import com.jspgou.cms.entity.StoreExt;
import com.jspgou.cms.entity.StoreModel;
import com.jspgou.cms.entity.StoreTxt;
import com.jspgou.cms.manager.CategoryMng;
import com.jspgou.cms.manager.StoreMng;
import com.jspgou.cms.manager.StoreModelMng;
import com.jspgou.common.page.Pagination;
import com.jspgou.common.web.CookieUtils;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.EmailSender;
import com.jspgou.core.entity.Global;
import com.jspgou.core.entity.Website;
import com.jspgou.core.manager.LogMng;
import com.jspgou.core.web.SiteUtils;
import com.jspgou.core.web.WebErrors;

@Controller
public class StoreAct {
	private static final Logger log = LoggerFactory.getLogger(StoreAct.class);
	
	@RequestMapping("/store/v_left.do")
	public String left(HttpServletRequest request, ModelMap model) {
		List<Category> list = categoryMng.getTopList(SiteUtils
				.getWebId(request));
		// 如果没有商品类别，则不传递数据到视图层，由视图层给出相应提示。
		if (list.size() > 0) {
			Category treeRoot = new Category();
			treeRoot.setName(MessageResolver.getMessage(request,
					"product.allCategory"));
			treeRoot.setChild(new LinkedHashSet<Category>(list));
			model.addAttribute("treeRoot", treeRoot);
		}
		return "store/left";
	}
	
	@RequestMapping("/store/v_list.do")
	public String list(Long ctgId,Boolean examine,Integer pageNo, 
			HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPage(ctgId,examine,false,cpn(pageNo), CookieUtils
				.getPageSize(request));
		model.addAttribute("pagination",pagination);
		model.addAttribute("ctgId",ctgId);
		model.addAttribute("pageNo",pageNo);
		return "store/list";
	}
	
	@RequestMapping("/store/v_forbiddenlist.do")
	public String forbiddenlist(Boolean forbidden,Integer pageNo, 
			HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPage(null,null,true,cpn(pageNo), CookieUtils
				.getPageSize(request));
		model.addAttribute("pagination",pagination);
		model.addAttribute("pageNo",pageNo);
		return "store/forbiddenlist";
	}
	
	@RequestMapping("/store/v_unfreeze.do")
	public String unfreeze(Long id,Boolean forbidden,Integer pageNo, 
			HttpServletRequest request, ModelMap model) {
		Store bean = manager.findById(id);
		bean.setForbidden(forbidden);
		manager.update(bean);
		model.addAttribute("pageNo",pageNo);
		return "redirect:v_forbiddenlist.do";
	}
	
	@RequestMapping("/store/v_view.do")
	public String view(Long id,HttpServletRequest request,ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		Store store=manager.findById(id);
		String uploadRoot=web.getUploadUrl();
		model.addAttribute("uploadRoot", uploadRoot);
		model.addAttribute("store", store);
		return "store/view";
	}

	@RequestMapping("/store/v_add.do")
	public String add(HttpServletRequest request,ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		String uploadRoot=web.getUploadUrl();
		model.addAttribute("uploadRoot", uploadRoot);
		List<Category> categoryList=categoryMng.getList(web.getId());
		model.addAttribute("categoryList", categoryList);
		return "store/add";
	}

	@RequestMapping("/store/v_edit.do")
	public String edit(Long id,Long ctgId,
			HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Store store=manager.findById(id);
		String uploadRoot=web.getUploadUrl();
		model.addAttribute("uploadRoot", uploadRoot);
		List<Category> categoryList=categoryMng.getList(web.getId());
		model.addAttribute("categoryList", categoryList);
		model.addAttribute("store",store);
		if(store.getModelpermission()){
			List<StoreModel> smlist=storeModelMng.getList();
			model.addAttribute("smlist", smlist);
		}else{
			StoreModel storeModel=storeModelMng.getByDefaultModel(true);
			if(storeModel==null){
				storeModel=storeModelMng.getList().get(0);
			}
			model.addAttribute("storeModel", storeModel);
		}
		model.addAttribute("ctgId", ctgId);
		return "store/edit";
	}

	@RequestMapping("/store/o_save.do")
	public String save(Store bean, StoreExt ext,StoreTxt txt,Long categoryId,
			HttpServletRequest request, ModelMap model) throws IOException {
		Website web = SiteUtils.getWeb(request);
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Global global=SiteUtils.getWeb(request).getGlobal();
		//设计店铺域名前缀
		String domainPreFix=global.getDomainPrefix();
		bean = manager.register(bean,ext,txt,null,domainPreFix,web,categoryId,true);
		log.info("save Store id={}", bean.getId());
		logMng.operating(request, "添加店铺", "id="+bean.getId()+" ;name="+bean.getStoreName());
		return "redirect:v_list.do";
	}

	@RequestMapping("/store/o_update.do")
	public String update(Store bean,StoreExt ext,StoreTxt txt, Long categoryId,Long storeModelId,
			Long ctgId,Integer pageNo, HttpServletRequest request,ModelMap model) {
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		storeModelId=null;
		bean = manager.updateAdm(bean,ext,txt,categoryId,storeModelId);
		log.info("update Store id={}.", bean.getId());
		logMng.operating(request, "修改店铺", "id="+bean.getId()+" ;name="+bean.getStoreName());
		return list(ctgId,true,pageNo, request, model);
	}
	
	@RequestMapping("/store/v_examine.do")
	public String examine(Long id,Long ctgId,Integer pageNo,
			HttpServletRequest request,ModelMap model) {
		Store bean=manager.findById(id);
		bean.setExamine(true);
		manager.update(bean);
		return list(ctgId,null,pageNo, request, model);
	}
   
	@RequestMapping("/store/v_examine1.do")
	public String examine1(Long id,Long ctgId,Integer pageNo,
			HttpServletRequest request,ModelMap model) {
		Store bean=manager.findById(id);
		bean.setExamine(false);
		manager.update(bean);
		model.addAttribute("store", bean);
		return "store/examine";
	}
	@RequestMapping("/store/sendEmail.do")
	public String examine2(Long id,Long ctgId,Integer pageNo,
			 final HttpServletRequest request,ModelMap model) {
		Store bean=manager.findById(id);
		String title=request.getParameter("title");
		String content=request.getParameter("content");
		bean.setExamine(false);
		manager.update(bean);	
		model.addAttribute("store", bean);
		Website web = SiteUtils.getWeb(request);
		final EmailSender email = web.getEmailSender();		
		      final String to=bean.getMember().getEmail();
			JavaMailSenderImpl sender = new JavaMailSenderImpl(); // JavaMailSender用来发送邮件的类
			sender.setHost(email.getHost());// 服务器邮箱地址
			sender.setUsername(email.getUsername());// 用户名
			sender.setPassword(email.getPassword());// 密码
			sender.send(new MimeMessagePreparator() { // 邮件模板，支持文本、附件、html、图片等
				public void prepare(MimeMessage mimemessage)
						throws MessagingException, UnsupportedEncodingException {
					MimeMessageHelper msg = new MimeMessageHelper(mimemessage,
							false, email.getEncoding());// 创建MimeMessageHelper对象，处理MimeMessage的辅助类
					// 使用辅助类MimeMessage设定参数
					String title=request.getParameter("title");
					msg.setSubject(title);// 邮件设置邮件主题
					msg.setTo(to);// 设置接收方的email地址
					msg.setFrom(email.getUsername(), email.getPersonal());// 邮件的发件人	
					String content=request.getParameter("content"); // 邮件正文
					msg.setText(content, true);// 将发送的内容赋值给MimeMessageHelper,后面的true表示内容解析成html

				}
				
			});
			logMng.operating(request, "JSPGOU消息", "id="+bean.getId()+" ;name="+"XX"); 
	
		return "store/examine";
	}
	
	
	
	
	
	
	@RequestMapping("/store/o_delete.do")
	public String delete(Long[] ids, Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Store[] beans = manager.deleteByIds(ids);
		for (Store bean : beans) {
			log.info("delete Store id={}", bean.getId());
			logMng.operating(request, "删除店铺", "id="+bean.getId()+" ;name="+bean.getStoreName());
		}
		return list(null,true,pageNo, request, model);
	}

	private WebErrors validateSave(Store bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
//		Website web = SiteUtils.getWeb(request);
//		bean.setWebsite(web);
		return errors;
	}
	
	private WebErrors validateEdit(Long id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		if (vldExist(id, web.getId(), errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Long id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		if (vldExist(id, web.getId(), errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateDelete(Long[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		Website web = SiteUtils.getWeb(request);
		errors.ifEmpty(ids, "ids");
		for (Long id : ids) {
			vldExist(id, web.getId(), errors);
		}
		return errors;
	}

	private boolean vldExist(Long id, Long webId, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		Store entity = manager.findById(id);
		if(errors.ifNotExist(entity, Store.class, id)) {
			return true;
		}
//		if (!entity.getWebsite().getId().equals(webId)) {
//			errors.notInWeb(Store.class, id);
//			return true;
//		}
		return false;
	}
	
	@Autowired
	private StoreMng manager;
	@Autowired
	private CategoryMng categoryMng;
	@Autowired
	private StoreModelMng storeModelMng;
	@Autowired
	private LogMng logMng;

}